package cn.org.mrliu.ssm.common.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 打印所有请求参数
 * 
 * @author MrLiu
 *
 */
public class RequestParameterFilter implements Filter {
	private static Logger log = LoggerFactory.getLogger(RequestParameterFilter.class);
	private String[] exclusionArray;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// exclusions
		String exclusions = filterConfig.getInitParameter("exclusions");
		if (exclusions == null || exclusions.trim().length() == 0) {
			return;
		}
		exclusionArray = exclusions.split(",");
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String path = request.getServletPath();
		boolean isExclusion = false;
		if (exclusionArray != null && exclusionArray.length > 0) {
			for (String exclusion : exclusionArray) {
				if (path.startsWith(exclusion)) {
					isExclusion = true;
				}
			}
		}
		if (isExclusion) {
			filterChain.doFilter(servletRequest, servletResponse);
		} else {

			log.info("---------------------------------- request start ----------------------------------");
			log.info("path:" + request.getServletPath());
			Map<String, String[]> paramsMap = request.getParameterMap();
			if (paramsMap != null && paramsMap.size() > 0) {
				log.info("params:" + paramsMap.size());
				for (Entry<String, String[]> kv : paramsMap.entrySet()) {
					String key = kv.getKey();
					String[] values = kv.getValue();
					if (values == null) { // 没有值
						log.info(key);
					} else if (values.length > 1) { // 多个值
						log.info(key + ":" + Arrays.toString(values));
					} else { // 一个值
						log.info(key + ":" + values[0]);
					}
				}
			}
			log.info("---------------------------------- request end ----------------------------------");

			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	@Override
	public void destroy() {

	}
}
